import { defineStore } from 'pinia'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { chatApi, type Model } from '@/services/chat'

export const useApiKeyStore = defineStore('apiKey',
  () => {
    // 状态
    const apiKey = ref('')
    const isKeyVerified = ref(false)
    const isVerifying = ref(false)
    const isInitializing = ref(false)
    const hasInitialized = ref(false)
    const availableModels = ref<{ label: string, value: string }[]>([])
    const selectedModel = ref('models/gemini-2.0-flash')

    // API服务
    const verifyApiKey = async (key: string) => {
      if (!key.trim()) {
        ElMessage.warning('请输入API Key')
        return false
      }

      isVerifying.value = true

      try {
        const response = await chatApi.validateKey(key)
        const { success, models, error } = response.data

        if (success && models) {
          apiKey.value = key
          isKeyVerified.value = true
          availableModels.value = models.map((model: Model) => ({
            label: model.displayName,
            value: model.name
          }))
          selectedModel.value = availableModels.value[0]?.value || ''
          ElMessage.success('API Key验证成功')
          return true
        } else {
          throw new Error(error)
        }
      } catch (error: any) {
        console.error('API Key验证失败:', error)
        ElMessage.error(error?.message || 'API Key验证失败')
        return false
      } finally {
        isVerifying.value = false
      }
    }

    const setModel = async (model: string) => {
      try {
        await chatApi.setModel({ model })
        selectedModel.value = model
        ElMessage.success('模型切换成功')
        return true
      } catch (error: any) {
        console.error('模型切换失败:', error)
        ElMessage.error(error?.message || '模型切换失败')
        return false
      }
    }

    // 清除存储的API Key和验证状态
    const clearApiKeyData = () => {
      apiKey.value = ''
      isKeyVerified.value = false
      availableModels.value = []
      selectedModel.value = ''
      hasInitialized.value = false
      return true
    }

    // 初始化函数
    const initialize = async () => {
      // 如果已经初始化过或正在初始化中，则不再重复执行
      if (hasInitialized.value || isInitializing.value) {
        console.log('API Key已初始化或正在初始化中，跳过重复初始化')
        return true
      }

      // 如果已经从localStorage恢复了有效数据，则标记为已初始化
      if (isKeyVerified.value) {
        console.log('从持久化存储恢复API Key数据')
        hasInitialized.value = true
        return true
      }

      // 设置初始化标志
      isInitializing.value = true

      try {
        const configResponse = await chatApi.getConfig()
        if (configResponse.data?.success && configResponse.data?.config) {
          const { api_key, current_model } = configResponse.data.config

          if (api_key) {
            apiKey.value = api_key
            await verifyApiKey(api_key)
          }

          if (current_model) {
            selectedModel.value = current_model
          }
        }
        hasInitialized.value = true
        return true
      } catch (error) {
        console.error('初始化API配置失败:', error)
        return false
      } finally {
        isInitializing.value = false
      }
    }

    return {
      apiKey,
      isKeyVerified,
      isVerifying,
      isInitializing,
      hasInitialized,
      availableModels,
      selectedModel,
      verifyApiKey,
      setModel,
      initialize,
      clearApiKeyData
    }
  },
  {
    persist: {
      key: 'api_key_data',
      storage: localStorage,
      // 指定要持久化的状态路径（不用paths，而是用pick）
      pick: ['apiKey', 'isKeyVerified', 'availableModels', 'selectedModel']
    }
  })
